<template>
  <div
    class="scan-input-box"
    :class="disabled ? 'scan-input-box-disabeld' : ''"
  >
    <el-input
      ref="codeInput"
      v-model="code"
      :clearable="true"
      style="width: 400px"
      :disabled="disabled"
      placeholder="请扫码或输入资产编码"
      @keyup.enter.native="sacn"
      @input="(e) => (code = validSe(e))"
    >
      <template #prepend>资产编码</template>
    </el-input>
  </div>
</template>

<script setup name="ScanInputBox">
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  query: {
    type: Object,
    default: undefined,
  },
  api: {
    type: Function,
    default: undefined,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})
const code = ref('')
function sacn() {
  if (!code.value) {
    proxy.$message({
      message: '请扫描资产编码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let params = proxy.$fn.deepClone(props.query)
  params.code = proxy.$fn.setTrim(code.value)
  props
    .api(params)
    .then((res) => {
      if (res && res.success && res.data && res.data.length) {
        scanResult(res.data[0].assetCode)
      }
      code.value = ''
    })
    .catch(() => {
      code.value = ''
    })
}

function scanResult(code) {
  emits('callback', code, (val) => {
    if (val) {
      proxy.$message({
        message: `扫码成功`,
        type: 'success',
        duration: 3500,
        showClose: true,
      })
    } else {
      proxy.$message({
        message: `该扫码资产不在当前盘点任务范围类`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
    }
  })
}
</script>

<style scoped></style>
